package com.xiguaji.tiktok.v1.web.ins;

import com.xiguaji.tiktok.config.Config;
import com.xiguaji.tiktok.v1.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.math.BigInteger;

@RequestMapping("/instagram")
public class InsBaseController extends BaseController {

    /**
     * config
     */
    @Autowired
    private Config config;

    /**
     * 判断图片是否过期，未过期则返回原数据，否则返回过期的图片
     * @param url
     * @param type
     * @param size
     * @return
     */
    public String getNoExpiredImage(String url,int type,int size){
        if(StringUtils.isEmpty(url)){
            return getDefaultImage(type,size);
        }
        int expireTimeIndex = url.indexOf("oe=");
        if(expireTimeIndex == -1){
            return url;
        }
        expireTimeIndex += 3;
        String expireTimeString = url.substring(expireTimeIndex,expireTimeIndex + 8);
        try {
            long expireTime = new BigInteger(expireTimeString,16).longValue();
            long nowTime = System.currentTimeMillis() / 1000 - 3600;
            if(expireTime < nowTime){
                return getDefaultImage(type,size);
            }
        }catch (Exception e){
            return getDefaultImage(type,size);
        }
        return url;
    }

    /**
     *
     * @param type
     * @param size
     * @return
     */
    public String getDefaultImage(int type,int size){
        if(type > 2 || type < 0){
            type = 0;
        }
        if(size > 2 || size < 0){
            size = 0;
        }
        switch (type){
            case 1 :{
                switch (size){
                    case 1: return config.getMediaImageMiddleUrl();
                    case 2: return config.getMediaImageLargeUrl();
                    default: return config.getMediaImageSmallUrl();
                }
            }
            case 2:{
                switch (size){
                    case 1: return config.getProductImageMiddleUrl();
                    case 2: return config.getProductImageLargeUrl();
                    default: return config.getProductImageSmallUrl();
                }
            }
            default:{
                switch (size){
                    case 1: return config.getBloggerMiddleImageUrl();
                    case 2: return config.getBloggerLargeImageUrl();
                    default: return config.getBloggerSmallImageUrl();
                }
            }
        }
    }
}
